
import Taro from '@tarojs/taro'
type Options = {
    classNote: string
    initNum: number
    limit: number
}

export default class LazyLoad {
	protected page: any
	protected classNote: any
	protected initNum: number
	protected limit: number
	protected intersectionObserver: any
	constructor(context, opt: Options){
		console.log(222,context, context.setState)
		this.page = context;

		this.classNote = opt.classNote || 'item-'
		this.initNum = opt.initNum || 5
		this.limit = opt.limit || 5

		this.intersectionObserver = {}
		console.log('this.page.setState', this.page.state)
		this.page.setState({
			__LAZT_LOAD_COUNT: this.initNum
		})

		if(!this.isSupport()) console.error('wx.createIntersectionObserver is not a function')

	}

	observe() {
		if(!this.isSupport()) return;

		this.intersectionObserver = wx.createIntersectionObserver();
		console.log('this.page.data.__LAZT_LOAD_COUNT', this.page.state.__LAZT_LOAD_COUNT)
		this.intersectionObserver.relativeToViewport({bottom: 100}).observe(this.classNote + this.page.state.__LAZT_LOAD_COUNT, (res) => {
			if(res.boundingClientRect.top > 0){
				this.intersectionObserver.disconnect()
				this.page.setState({
					__LAZT_LOAD_COUNT: this.page.state.__LAZT_LOAD_COUNT + this.limit
				})
				this.observe();
			}
		})
	}

	isSupport(){
		return !!wx.createIntersectionObserver
	}
}
